import React, { useState,useEffect } from 'react'
import { Cell, Input, Button, Checkbox, Toast } from 'zarm'
import CustomIcon from '@/components/CustomIcon'
// import Captcha from 'react-captcha-code'
import { post, get } from '@/utils'
//import cx from 'classnames'

import './style.less'

const Login = () => {
  const [userName, setUserName] = useState('')
  const [password, setPassword] = useState('')
  const [verify, setVerify] = useState('')
  const [type, setType] = useState('register')
  // let captcha = ''
  // const handleChange=useCallback((cap)=>{
  //     captcha=cap
  // },[])
  useEffect(()=>{
    document.title=type=='login'?'登录':'注册'
  },[type])
  const onSubmit = async () => {
    if (!userName) {
      Toast.show('请输入账号')
      return
    }
    if (!password) {
      Toast.show('请输入密码')
      return
    }
    
    try {
      if (type == 'login') {//登录
        const data = await post('/api/user/login',{
          username: userName,
          password
        })
        //console.log(data);
        //原生js跳转
        window.location.href='/'
        Toast.show(data.message)
        localStorage.setItem('token',data.data.token)
        
      } else {//注册
        if (!verify) {
          Toast.show('请输入验证码')
          return
        }
        // if(verify!=captcha){
        //     Toast.show('验证码错误')
        // }
        const data = await post('/api/user/register', { username: userName, password })
        Toast.show(data.message)
        setType('login')
      }

    } catch (error) {

    }

  }
  return <div className="auth">
    <div className="head" />
    <div className="tab">
      <span className={ type == 'login' ? 'avtive':''} onClick={() => setType('login')}>登录</span>
      <span className={type == 'register'?'avtive':'' } onClick={() => setType('register')}>注册</span>
    </div>
    <div className="form">
      <Cell icon={<CustomIcon type="zhanghao" />}>
        <Input
          clearable
          type="text"
          placeholder="请输入账号"
          onChange={(value) => setUserName(value)}
        />
      </Cell>
      <Cell icon={<CustomIcon type="mima" />}>
        <Input
          clearable
          type="password"
          placeholder="请输入密码"
          onChange={(value) => setPassword(value)}
        />
      </Cell>
      {
        type == 'register' ? <Cell icon={<CustomIcon type="mima" />}>
          <Input
            clearable
            type="text"
            placeholder="请输入验证码"
            onChange={(value) => setVerify(value)}
          />
          {/* <Captcha charNum={4} onChange={handleChange} /> */}
        </Cell> : null
      }

    </div>
    <div className="operation">
      {
        type == 'register' ? <div className="agree">
          <Checkbox />
          <label className="text-light">阅读并同意<a>《掘掘手札条款》</a></label>
        </div> : null
      }

      <Button block theme="primary" onClick={onSubmit}>{type == 'register' ? '注册' : '登录'}</Button>
    </div>
  </div>
}

export default Login